helpers do
  # Add h() and u() as helper methods.
  include ERB::Util 

  def consider_request
    throw :halt, :render_403 if (
      Kapow::Config.accept_iphod_requests_only &&
      !request.env["HTTP_USER_AGENT"].match(/Mobile.*Safari/)
    )
  end

  def path_from_params
    @path = params[:path] ? sanitize_path(params[:path]) : ''
    @archive = Archive.load(@path) if Archive.exists?(@path)
  end

  def sanitize_path(path)
    path_parts = path.split('/')
    path_parts = path_parts.reject {|part| part.match(/^\./)}
    File.join(path_parts)
  end

  def save_place(book, page)
    if response
      response.set_cookie('current_book', book)
      response.set_cookie('current_page', page)
    end
  end

  def get_place
    place = {}
    place[:book] = request.cookies['current_book']
    place[:page] = request.cookies['current_page']
    if place[:book] && place[:page]
      place[:page] = place[:page].to_i
      place
    else
      nil
    end
  end

  def sluggify(str, lim = 250)
    str.downcase.gsub(
      /[^a-z0-9\-]/, '-'
    ).gsub(
      /\-+/, '-'
    ).gsub(
      /\-$/, ''
    ).first(lim)
  end

  def link_to(link_text, root, queries = {}, attributes = {})
    if queries.any?
      qarr = []
      queries.each_pair {|qk,qv| qarr << "#{u(qk)}=#{u(qv)}"}
      qstr = '?' + qarr.join('&')
    end

    if attributes.any?
      aarr = []
      attributes.each_pair {|ak,av| aarr << "#{ak}=\"#{av}\""}
      astr = ' ' + aarr.join(' ')
    end

    %Q`<a href="#{root}#{qstr}"#{astr}>#{link_text}</a>`
  end

  def link_to_function(link_text, js, attributes = {})
    if attributes.any?
      aarr = []
      attributes.each_pair {|ak,av| aarr << "#{ak}=\"#{av}\""}
      astr = ' ' + aarr.join(' ')
    end

    %Q`<a href="#" onclick="#{js};return false;"#{astr}>#{link_text}</a>`
  end

  def escape_javascript(javascript)
    return '' if javascript.blank?
    javascript.gsub(
      '\\', '\0\0'
    ).gsub(
      /\r\n|\n|\r/, "\\n"
    ).gsub(/["']/) {|m| "\\#{m}"}
  end

  def render_403
    status 403
    body "<h1>Forbidden</h1>"
  end

  def render_404
    status 404
    body "<h1>Not Found</h1>"
  end

end
